<?php

if( !defined('IN_SEC') ){
	exit('Access Denied.');
}

class pager{

	var $uri;
	var $page;
	var $pages;
	var $amount;
	var $offset;
	var $pagezise;

	public function __construct(){
		$this->page = intval($_GET['page']);
		$this->page = $this->page ? $this->page : 1;
		$this->uri = $this->url($this->page);
	}

	public function url($page){
		$query_string = array();
		$uri = $_SERVER['REQUEST_URI'];
		$query = strpos($uri, '?');
		if ( $query ){
			$uri = substr($uri, $query + 1);
			parse_str($uri, $query_string);
		}
		$query_string['page'] = $page;

		return '?' . http_build_query($query_string);
	}

	public function init($amount = 1, $pagesize = 20){
		$this->amount = intval($amount);
		$this->pagesize = intval($pagesize);
		if ( $this->amount && $this->pagesize ){
			$this->pages = ceil($this->amount / $this->pagesize);
			$this->pages = $this->pages ? $this->pages : 1;
		}else{
			$this->pages = 1;
		}
		$this->page = ($this->page > $this->pages) ? $this->pages : $this->page;
		$this->offset = intval(($this->page - 1) * $this->pagesize);

		return array(
			'pages' => $this->pages(),
			'offset' => $this->offset,
			'pagesize' => $this->pagesize,
		);
	}

	public function pages(){

		if ( $this->pages <= 9 ){
			$range = range(1, $this->pages);
		}else{
			$min = $this->page - 4;
			$max = $this->page + 4;
			if ( $min < 1 ){
				$max += (4 - $min);
				$min = 1;
			}
			if ( $max > $this->pages ){
				$max = $this->pages;
			}
			$range = range($min, $max);
		}
		$pages = '<div class="pages clearfix"><ul class="pagination">';
		$pages .= "<li><a href=\"javascript:void(0);\">共".$this->amount."条记录</a><li>";
		if ($this->page > 1) {
			$pages .= "<li><a href='".$this->url(1)."'>首页</a><li><a href='".$this->url($this->page - 1)."'><i class=\"icon-double-angle-left\"></i></a>";
		}

		foreach( $range as $p ){
			if ( $this->page == $p ){
				$pages .= "<li class=\"active\"><a href=\"javascript:void(0);\">{$p}</a></li>";
			}else{
				$pages .= "<li><a href=\"".$this->url($p)."\">{$p}</a></li>";
			}
		}
		if ($this->page < $this->pages) {
			$pages .= "<li><a href='".$this->url($this->page + 1)."'><i class=\"icon-double-angle-right\"></i></a></li><li><a href='".$this->url($this->pages)."'>末页</a></li>";
		}

		$pages .= '</ul></div>';

		return $pages;
	}

}

?>